#include "VertexBuffer.h"
#include "..\utils\Logger.h"
#include "..\content\Material.h"
#include "..\utils\Log.h"

namespace ds {

VertexBuffer::VertexBuffer(D3DPRIMITIVETYPE primitiveType,bool dynamic) : m_Dynamic(dynamic) {
	LOG(logINFO) << "Creating new vertex buffer - dynamic: " << dynamic;
	vertexBuffer = NULL; 
	indexBuffer = NULL;
	m_numVertices = 0; 
	m_FVF = 0; 
	m_vertexSize = 0;
	m_useTexture = false;
	m_primitiveType = primitiveType;
}

VertexBuffer::~VertexBuffer() {
	Release();
}

void VertexBuffer::Release() {
	LOG(logINFO) << "Releasing vertex buffer";
	//SAFE_RELEASE( m_pVB ); 
	if( vertexBuffer ) { 
		vertexBuffer->Release(); 
		vertexBuffer = NULL; 
	} 
	m_numVertices = 0; 
	m_FVF = 0; 
	m_vertexSize = 0; 
	// IndexBuffer is released in CIndexBuffer 
	indexBuffer = NULL;	
}

void VertexBuffer::prepareData() {
	if ( m_numVertices > 0 ) {
		IDirect3DDevice9 * pDevice = gEngine->getDevice();
		if ( m_Dynamic ) {
			createBuffer();
			if ( indexBuffer ) {
				indexBuffer->init();
			}
		}
		pDevice->SetStreamSource( 0, vertexBuffer, 0, m_vertexSize ); 
		pDevice->SetFVF( m_FVF );	
	}
}

void VertexBuffer::render(UINT numPrimitives) {
	if ( m_numVertices > 0 ) {
		IDirect3DDevice9 * pDevice = gEngine->getDevice();
		if ( indexBuffer ) {
			HR(pDevice->SetIndices( indexBuffer->getIndexBuffer() )); 
			HR(pDevice->DrawIndexedPrimitive( m_primitiveType, 0, 0, m_numVertices, 0, numPrimitives ));
			gEngine->getDrawCounter()->addIndices(indexBuffer->getSize());
			gEngine->getDrawCounter()->addPrimitives(m_numVertices);
		} 
		else {
			HR(pDevice->DrawPrimitive(m_primitiveType,0,numPrimitives));
			gEngine->getDrawCounter()->addPrimitives(m_numVertices);
		}
		if ( m_useTexture ) {
			HR(pDevice->SetTexture( 0,NULL));
		}
	}
}

};
